/* $Revision: $ $Date: $
 * 
 * Copyright (C) 2009 Robert Stephan
 * 
 * This file is part of *** CaCaO - Card Catalogs Online ***
 *
 * CaCaO is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * CaCao is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package cacao.server;

import java.net.URL;
import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import cacao.client.data.CaCaOHelper;
import cacao.client.data.OrderObject;

public class CaCaOMailOrder {
	public static String execute(OrderObject order){
		try{
			ResourceBundle messages = ResourceBundle.getBundle("cacao.client.CaCaOMessages");
			try{
				Session mailSession = null;
				Properties cacaoprops = CaCaOServer.getInstance().getProperties();
				Properties props = new Properties();
				props.setProperty("mail.transport.protocol", cacaoprops.getProperty("CaCaO.server.ordermail.protocol"));
				props.setProperty("mail.smtp.host", cacaoprops.getProperty("CaCaO.server.ordermail.host"));
				props.setProperty("mail.smtp.port", cacaoprops.getProperty("CaCaO.server.ordermail.port"));
				if("true".equals(cacaoprops.getProperty("CaCaO.server.ordermail.starttls.enable"))){
					props.setProperty("mail.smtp.starttls.enable", "true");
				}

				final String user = cacaoprops.getProperty("CaCaO.server.ordermail.user");
				final String password = cacaoprops.getProperty("CaCaO.server.ordermail.password");
				boolean auth = "true".equals(cacaoprops.getProperty("CaCaO.server.ordermail.auth"));

				if(auth){
					props.setProperty("mail.smtp.auth", "true");
					mailSession = Session.getDefaultInstance(props,
							new javax.mail.Authenticator() {
						protected PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(user, password);
						}
					});
				}
				else{
					mailSession = Session.getDefaultInstance(props, null);
				}
						
				Transport transport = mailSession.getTransport();
				MimeMessage message = new MimeMessage(mailSession);
				message.setSubject(messages.getString("orderEmailSubject"));
				message.setFrom(new InternetAddress(cacaoprops.getProperty("CaCaO.server.ordermail.from")));
				String catalogcode = order.getCardID().split("_")[0];
				message.addRecipient(Message.RecipientType.TO, new InternetAddress(cacaoprops.getProperty("CaCaO.server.ordermail.to."+catalogcode)));
				message.addRecipient(Message.RecipientType.CC, new InternetAddress(cacaoprops.getProperty("CaCaO.server.ordermail.cc")));

				StringBuffer htmlText = new StringBuffer();
				htmlText.append(MessageFormat.format(messages.getString("orderEmailBody"), order.getCatalogue(),
						order.getCardID(), order.getIssue(),
						order.getName(), order.getFirstname(), 
						order.getUserID(), order.getEmail(), order.getComment()));
				htmlText.append("\n<br />");

				String cardurl = cacaoprops.getProperty("CaCaO.client.application.url")+"?card="+order.getCardID();
				htmlText.append("<a href='"+cardurl+"'>"+cardurl+"</a>");
				htmlText.append("\n<br />");
				int lastChunkLength = Integer.parseInt(cacaoprops.getProperty("CaCaO.client.file.lastchunklength").trim());
				boolean debug = "true".equals(cacaoprops.getProperty("CaCao.client.debug"));
				String url = cacaoprops.getProperty("CaCaO.client.file.url")+CaCaOHelper.generatePath(order.getCardID(), lastChunkLength, order.getExtension(), debug);
				htmlText.append("<image alt='"+MessageFormat.format(messages.getString("orderEmailImageAltText"),order.getCardID())+"' width='475px' src='cid:card-x' />");

				Multipart multipart = new MimeMultipart("related");
				MimeBodyPart htmlPart = new MimeBodyPart();
				htmlPart.setText(htmlText.toString(), "UTF-8", "html");
				multipart.addBodyPart(htmlPart);

				BodyPart imgPart = new MimeBodyPart();
				imgPart.setHeader("Content-ID", "card-x");
				DataSource ds = new URLDataSource(new URL(url));
				imgPart.setDataHandler(new DataHandler(ds));
				multipart.addBodyPart(imgPart);

				message.setContent(multipart);


				transport.connect();
				message.saveChanges();
				transport.sendMessage(message, message.getAllRecipients());
				transport.close();

				return null;
			}
			catch(Exception e){
				e.printStackTrace(System.err);
				return MessageFormat.format("orderEmailFailure", e.getMessage());
			}
		}
		catch(MissingResourceException e){
			System.err.println("Could not find message files.");
			return MessageFormat.format("orderEmailFailure", e.getMessage());
		}
	}

	public static String executeOld(OrderObject order){
		try{
			ResourceBundle messages = ResourceBundle.getBundle("cacao.client.CaCaOMessages");
			try{
				Properties cacaoprops = CaCaOServer.getInstance().getProperties();
				Properties props = new Properties();
				props.setProperty("mail.transport.protocol", cacaoprops.getProperty("CaCaO.server.ordermail.protocol"));
				props.setProperty("mail.host", cacaoprops.getProperty("CaCaO.server.ordermail.host"));

				Session mailSession = Session.getDefaultInstance(props, null);
				Transport transport = mailSession.getTransport();
				MimeMessage message = new MimeMessage(mailSession);
				message.setSubject(messages.getString("orderEmailSubject"));
				message.setFrom(new InternetAddress(cacaoprops.getProperty("CaCaO.server.ordermail.from")));
				message.addRecipient(Message.RecipientType.TO, new InternetAddress(cacaoprops.getProperty("CaCaO.server.ordermail.to")));

				StringBuffer htmlText = new StringBuffer();
				htmlText.append(MessageFormat.format(messages.getString("orderEmailBody"), order.getCatalogue(),
						order.getCardID(), order.getIssue(),
						order.getName(), order.getFirstname(), 
						order.getUserID(), order.getEmail(),
						order.getComment()));
				htmlText.append("\n<br /><br />");


				int lastChunkLength = Integer.parseInt(cacaoprops.getProperty("CaCaO.client.file.lastchunklength").trim());
				boolean debug = "true".equals(cacaoprops.getProperty("CaCao.client.debug"));
				String url = cacaoprops.getProperty("CaCaO.client.file.url")+CaCaOHelper.generatePath(order.getCardID(), lastChunkLength, order.getExtension(), debug);

				htmlText.append("<a href='"+url+"'>"+url+"</a>");

				htmlText.append("\n<br />");

				htmlText.append("<image alt='"+MessageFormat.format(messages.getString("orderEmailImageAltText"),order.getCardID())+"' width='500px' src='"+url+"' />");

				message.setContent(htmlText.toString(), "text/html");

				transport.connect();
				transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
				transport.close();

				return null;
			}
			catch(Exception e){
				e.printStackTrace(System.err);
				return MessageFormat.format("orderEmailFailure", e.getMessage());
			}
		}
		catch(MissingResourceException e){
			System.err.println("Could not find message files.");
			return MessageFormat.format("orderEmailFailure", e.getMessage());
		}
	}
}
